
#import "CodeInputView.h"
#import <Masonry/Masonry.h>
#import "CustomTextView.h"
#import "UIView+Util.h"
#import "CodeView.h"

#define MaxLength 4

@interface CodeInputView () <UITextViewDelegate>
@property (nonatomic, strong) UIView *codeBGView; // 验证码基础视图
@property (nonatomic, strong) CustomTextView *textView; // 输入框
@end

@implementation CodeInputView

- (instancetype)init
{
    self = [super init];
    if (self) {
        // 初始化视图
        [self initView];
    }
    return self;
}

/** 初始化视图 */
- (void)initView {
    [self textView];
    // 键盘弹框
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self beginEdit];
    });
    // 临时view,用于布局
    UIView *tempView;
    for (int i = 0; i < MaxLength; i++) {
        CodeView *codeView = [CodeView codeView];
        codeView.tag = i;
        [self.codeBGView addSubview:codeView];
        [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.and.height.mas_equalTo(kCodeViewWidth);
            make.top.equalTo(self.codeBGView);
            
            if (tempView) {
                make.left.equalTo(tempView.mas_right).offset(kCodeMarginLeft);
            } else {
                make.left.equalTo(self.codeBGView).offset(kCodePadding);
            }
        }];
        tempView = codeView;
        // 给每个验证框绑定点击事件
        [codeView tapUpWithBlock:^(UIView * view) {
            // 取出上一个验证框,还原,self.codeBGView中第一个为textView,故取后面的验证验证框需要+1
//            CodeView *lastCodeView = self.codeBGView.subviews[self.textView.index + 1];
//            [lastCodeView setCodeLineColor:[UIColor grayColor]];
            
            // 设置当前点击的验证框,设置颜色并记录索引,用于设置光标位置
            CodeView *nowCodeView = (CodeView *)view;
//            [nowCodeView setCodeLineColor:[UIColor greenColor]];
            self.textView.index = view.tag;
            
            // 如果有该验证框有文字则光标在右边,否则在左边
            UILabel *label = nowCodeView.subviews.firstObject;
            self.textView.inRight = label.text.length != 0;
            
            // 为了光标布局
            [self endEdit];
            [self beginEdit];
        }];
    }
}


#pragma mark - method
- (void)beginEdit {
    [self.textView becomeFirstResponder];
}
- (void)endEdit {
    [self.textView resignFirstResponder];
}

// 取出可复制
    //-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
    //{
    //    return NO;
    //}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // 用于保存验证框中的内容
    NSMutableString *strM = [NSMutableString string];
    // 用于记录当前改变的验证框中是否有内容
    BOOL hasText = NO;
    // 遍历所有的验证框
    for (int i = 0; i < MaxLength; i ++) {
            UIView *view = [self.codeBGView.subviews objectAtIndex:i +1];
            UILabel *label = [view.subviews objectAtIndex:0];
            if (self.textView.index == i) { // 赋值当前的验证框,并记录当前验证框是否有内容
                hasText = label.text.length != 0;
                label.text = text;
            }
            if (label.text.length != 0) { // 将验证框中的内容拼接起来
                [strM appendString:label.text];
            }
    }
    
    // 改变上一个验证框的颜色
//    CodeView *lastCodeView = self.codeBGView.subviews[self.textView.index + 1];
//    [lastCodeView setCodeLineColor:[UIColor grayColor]];
    
    // text有值说明输入,没有值则是删除
    if (text.length != 0) { // 输入
        self.textView.index ++;
        if (strM.length >= MaxLength) { // 如果文字为MaxLength,则输入完毕,回调
            [self endEdit];
            if (self.inputViewBlock) {
                self.inputViewBlock(strM, self.phone);
            }
            self.textView.index = 0; // 初始化索引,防止数组越界
            return YES;
        } else { // 文字不够MaxLength,输入后从左到右跳入第一个空白的输入框
            for (int i = 0; i < MaxLength; i ++) {
                UIView *view = [self.codeBGView.subviews objectAtIndex:i +1];
                UILabel *label = [view.subviews objectAtIndex:0];
                if (label.text.length == 0) { // 记录第一个空白的输入框,便于光标跳入
                    self.textView.index = i;
                    break;
                }
            }
        }
    } else { // 删除操作
        
        if (self.textView.index != 0) { // 第一个输入框删除不做处理
            if (!hasText) { // 该输入框如果没有内容,则清除上一个输入框中的内容
                self.textView.index -= 1;
                UIView *view = self.codeBGView.subviews[self.textView.index + 1];
                UILabel *label = [view.subviews objectAtIndex:0];
                 hasText = label.text.length != 0;
                label.text = @"";
            }
        }
    }
    
    // 设置当前输入框下划线颜色
//    CodeView *nowCodeView = self.codeBGView.subviews[self.textView.index + 1];
//    [nowCodeView setCodeLineColor:[UIColor greenColor]];
    // 不管插入还是删除光标都在中间
    self.textView.inRight = NO;
    
    // 当text中没有文字,点击删除则不会自动布局光标,故在此判断
    if (text.length == 0 && self.textView.text.length == 0) {
        [self endEdit];
        [self beginEdit];
    }

    return YES;
}

#pragma mark - 懒加载
- (UIView *)codeBGView {
    if (!_codeBGView) {
        _codeBGView = [[UIView alloc] init];
        _codeBGView.backgroundColor = [UIColor clearColor];
        [self addSubview:_codeBGView];
        [_codeBGView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return _codeBGView;
}
- (CustomTextView *)textView {
    if (!_textView) {
        _textView = [[CustomTextView alloc] init];
        _textView.delegate = self;
        [self.codeBGView addSubview:_textView];
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.width.height.equalTo(self.codeBGView);
        }];
    }
    return _textView;
}
@end
